package com.hqs.rxjava;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

import com.hqs.common.utils.Log;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Converter;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.Result;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

public class RetrofitActivity extends AppCompatActivity {

    @BindView(R.id.tv_result)
    TextView tvResult;

    private Disposable disposable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_retrofit);

        ButterKnife.bind(this);
    }

    @OnClick(R.id.button)
    void buttonClick(){

        // 单独使用 Retrofit

//        retrofit();


        // Retrofit + RxJava

        rxJava();
    }

    void retrofit(){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://www.baidu.com/")
                .build();
        GithubService service = retrofit.create(GithubService.class);
        service.content().enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    tvResult.setText(response.body().string());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
    }

    void rxJava(){

        if (disposable == null){
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl("https://www.baidu.com/")
                    .addConverterFactory(StringConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();

            GithubService service = retrofit.create(GithubService.class);

            service.contentRxJava()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .onTerminateDetach()
                    .subscribe(new Observer<Result<String>>() {
                        @Override
                        public void onSubscribe(@NonNull Disposable d) {
                            disposable = d;
                        }

                        @Override
                        public void onNext(@NonNull Result<String> s) {
                            try {
                                tvResult.setText(s.response().body());
                            } catch (Exception e) {
                                tvResult.setText(e.getMessage());
                            }

                        }

                        @Override
                        public void onError(@NonNull Throwable e) {
                            tvResult.setText(e.getMessage());
                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        }
    }

    // 自定义StringConverter
    static class StringConverter extends Converter.Factory implements Converter<ResponseBody, String>{

        public static final StringConverter INSTANCE = new StringConverter();

        @Override
        public String convert(ResponseBody value) throws IOException {
            if (value != null){
                return value.string();
            }
            return "null";
        }
    }

    public static class StringConverterFactory extends Converter.Factory {

        public static final StringConverterFactory INSTANCE = new StringConverterFactory();

        public static StringConverterFactory create() {
            return INSTANCE;
        }

        // 我们只关实现从ResponseBody 到 String 的转换，所以其它方法可不覆盖
        @Override
        public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
            if (type == String.class) {
                return StringConverter.INSTANCE;
            }
            return null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (disposable != null){
            disposable.dispose();
        }
    }
}
